package com.seasugar.raggie.filter;

import com.alibaba.fastjson.JSON;
import com.seasugar.raggie.common.BaseContext;
import com.seasugar.raggie.common.R;
import com.seasugar.raggie.model.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebFilter(filterName = "loginCheckFilter",urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter{
    //路径匹配器，支持通配符
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request=(HttpServletRequest) servletRequest;
        HttpServletResponse response=(HttpServletResponse) servletResponse;
        //获取本次请求的URI

        ///employee/logout
        String requestURI=request.getRequestURI();

        //http://localhost:8080/employee/logout
//        String requestURL = request.getRequestURL().toString();

        log.info("拦截到请求：{}",requestURI);
        //不用拦截的请求
        String[] urls=new String[]{
                "/employee/login",
                "/employee/logout",
                "/user/sendMsg",
                "/user/login",
//                "/backend/page/login/login.html"
                "/backend/**",
                "/front/**",
        };

        //2、判断本次请求是否需要处理
        boolean check = check(urls, requestURI);
        if(check) {
            filterChain.doFilter(request, response);
            log.info("本次请求{}不需要处理",requestURI);
            return;
        }

        //backend
        //判断登录状态，如果已登录，则直接放行
        Object employee = request.getSession().getAttribute("employee");
        if(employee!=null){
            BaseContext.setCurrentId((Long) employee);
            log.info("本次请求{}不需要处理",requestURI);
            filterChain.doFilter(request,response);
            return;
        }

        //front
        User user = (User) request.getSession().getAttribute("user");
        if(user!=null){
            BaseContext.setCurrentId(user.getId());
            log.info("登录用户Id为：{}",user);
            filterChain.doFilter(request,response);
            return;
        }

        log.info("用户未登录");
        //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;

    }


//        //2、判断本次请求是否需要处理
//        boolean check = check(urls, requestURI);
//        if(check) {
//            filterChain.doFilter(request, response);
//            log.info("本次请求{}不需要处理",requestURI);
//            return;
//        }

        //出现的问题：如果这里不添加else判断而是让他继续下去，在前台登录的时候，后台可以随意登录，这样是不对的

//        //backend
//        //判断登录状态，如果已登录，则直接放行
//        Object employee = request.getSession().getAttribute("employee");
//        if(employee!=null){
//            //记得最前面的/
//            String url="/backend/**";
//            boolean b = PATH_MATCHER.match(url, requestURI);
//            if(b) {
//                BaseContext.setCurrentId((Long) employee);
//                log.info("本次请求{}不需要处理", requestURI);
//                filterChain.doFilter(request, response);
//                return;
//            }else{
//                log.info("用户未登录");
//                //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
//                response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
//                return;
//            }
//        }
//
//        //front
//        Object user = request.getSession().getAttribute("user");
//        if(user!=null){
////            String url="/front/**";
////            boolean b = PATH_MATCHER.match(url, requestURI);
////            log.info("登录用户Id为：{}",user);
//            filterChain.doFilter(request,response);
//            return;
//        }else {
//            log.info("用户未登录");
//            //5、如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据
//            response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
//            return;
//        }



    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestURI
     * @return
     */
    public boolean check(String[] urls,String requestURI){
        for (String url : urls) {
            boolean match = PATH_MATCHER.match(url, requestURI);
            if(match)
                return true;
        }
        return false;
    }
}
